package com.xiaotu.storage.converter;

import com.xiaotu.common.exception.SpiderException;
import com.xiaotu.common.exception.SpiderExceptionCode;
import com.xiaotu.common.util.MathUtil;
import com.xiaotu.common.util.RegexUtils;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;

/**
 * 百分比转换器
 *
 * @auther GaoHJ
 * @create 2017/11/22
 */
@Component("RateConverter")
public class RateConverter extends NumberFormateConverter
{
    private static final String RATE = "%";

    @Override
    protected Object doConvert(String value, JSONObject target, boolean needThrow)
    {
        if (!RegexUtils.regexMatch(RegexUtils.REGEX_NUMBER + RATE, value) && !RegexUtils
                .regexMatch(RegexUtils.REGEX_NUMBER, value))
        {
            if (needThrow)
                throw new SpiderException(SpiderExceptionCode.RateFormateException, "value:" +
                        value);
            return value;
        }

        Object res = super.doConvert(RegexUtils.regexSearch(RegexUtils.REGEX_NUMBER, value),
                target, needThrow);
        if (res instanceof Number)
            return MathUtil.div(res, 100);
        return res;
    }
}
